//
//  MineViewController.m
//  植物管理
//
//  Created by liujianlong on 2022/11/21.
//

#import "MineViewController.h"
#import "MineCell.h"
#import "PrivateViewController.h"
#import "ScoreViewController.h"
#import "PlantViewController.h"
#import "TongJiViewController.h"

@interface MineViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) IBOutlet UIButton *avatar;
@property (strong, nonatomic) IBOutlet UIImageView *bgImg;
@property (strong, nonatomic)  NSArray *titles;
@property (strong, nonatomic)  NSArray *imgs;
@property (strong, nonatomic)  NSArray *colors;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)initUI{
    self.titles = @[@"统计",@"花记",@"给好评",@"隐私政策"];
    self.imgs = @[@"统计",@"花记",@"给好评",@"隐私政策"];
    self.colors = @[@"#E9F4EC",@"#FFE7E7",@"#FAE7D2",@"#C2E2FF"];
    [self.avatar setImage:[UIImage imageWithData:APP.user.headImg] forState:UIControlStateNormal];
    self.collectionView.scrollEnabled = NO;
    self.collectionView.c_top.equalTo(self.bgImg.c_bottom);
    self.collectionView.c_left.equalTo(self.view);
    self.collectionView.c_right.equalTo(self.view);
    self.collectionView.c_bottom.equalTo(self.view);
    [self.collectionView registerNib:[MineCell nib] forCellWithReuseIdentifier:[MineCell ID]];
}

- (IBAction)actionForBtn:(UIButton *)sender {
    if (sender.tag == 201) {
        [self backBtnAction];
    }else{
        WS(self)
        SheetViewController *sheetvc = [SheetViewController new];
        sheetvc.withCancel = NO;
        sheetvc.array = @[@"拍摄",@"相册"];
        sheetvc.block = ^(int index, NSString * _Nonnull text) {
            NSString *mediaType = AVMediaTypeVideo; //读取媒体类型
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType]; //读取设备授权状态
            if (authStatus == AVAuthorizationStatusNotDetermined || authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) { // 授权受阻
                UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:LS(@"是否开启相机访问权限？") message:nil
                                                                           preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *OFF = [UIAlertAction actionWithTitle:LS(@"取消") style:UIAlertActionStyleDefault handler:nil];
                UIAlertAction *ON = [UIAlertAction actionWithTitle:LS(@"确定") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { // 设置权限
                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:url]) {
                        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                            // do something
                        }];
                    }
                }];
                [alterCon addAction:OFF];
                [alterCon addAction:ON];
                [self presentViewController:alterCon animated:YES completion:nil];
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [CCHud startHud];
                });
                UIImagePickerController *vc = [UIImagePickerController new];
                vc.delegate = weakself;
                vc.allowsEditing = YES;
                vc.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
                vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [[weakself currentVC] presentViewController:vc animated:YES completion:^{
                    [CCHud stopHud];
                }];
            }
            
        };
        [[weakself currentVC] presentViewController:sheetvc animated:NO completion:nil];
    }
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.5);
    User *user = APP.user;
    user.headImg = data;
    APP.user = user;
    [self.avatar setImage:img forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.titles.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MineCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[MineCell ID] forIndexPath:indexPath];
    cell.title.text = LS(self.titles[indexPath.row]);
    cell.img.image = [UIImage imageNamed:self.imgs[indexPath.row]];
    cell.bgHexColor = self.colors[indexPath.row];
    return  cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    WS(self);
    NSString *title = self.titles[indexPath.row];
    if ([title isEqualToString:@"统计"]) {
        TongJiViewController *vc = [TongJiViewController new];
        [self push:vc :YES];
    }else if ([title isEqualToString:@"花记"]){
        PlantViewController *vc = [PlantViewController new];
        [self push:vc :YES];
    }else if ([title isEqualToString:@"给好评"]){
        ScoreViewController *vc = [ScoreViewController new];
        [self presentViewController:vc animated:NO completion:nil];
    }else if ([title isEqualToString:@"隐私政策"]){
        PrivateViewController *vc = [PrivateViewController new];
        [self push:vc :YES];
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat w = (SCREEN_WIDTH - 60) / 2;
    return  CGSizeMake(w, w);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(0, 20, 20, 20);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
@end
